<?php
namespace cms\modules\v1\models\userFund;

use cms\modules\v1\models\user\UserReal;
use common\models\CacheKeys;
use common\models\Functions;
use common\models\pay\Alipay;
use common\models\Status;
use common\models\user\User;
use common\models\userFund\UserWithdrawOrder;
use Yii;
use yii\base\Exception;
use yii\helpers\ArrayHelper;

/**
 * This is the model class for table "user_transfer_info".
 *
 * @property int $id
 * @property string $name
 */
class WithdrawOrder extends UserWithdrawOrder
{
    /**
     * 返回列表数据
     * @param int $page
     * @param int $size
     * @return array
     */
    public function getListData($page = 1, $size = 20) {
        try {
            //搜索条件
            $searchWhere  = $this->getSearch();//自定义搜索条件
            //得到文章的总数
            $count = static::getObjectCountByAndWhere($searchWhere['where'], $searchWhere['andWhere'])->count();
            $data = static::setPageinationAPI($page, $size, $count);
            //设置分页
            $offset = ($page - 1) * $size;

            //排序 order
            $orderSql = 'status ASC, create_time DESC';

            $query = static::getObjectByAndWhere($searchWhere['where'],$searchWhere['andWhere'], '*', $orderSql, $offset, $size);

            $data['data'] = $this->handelList($query);

            return Functions::formatRestAPI(0, '', $data);
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 自定义参数的搜索  搜索,搜索也分每一列
     * 这里要根据业务逻辑进行修改
     * @param $search
     * @return string
     */
    public function getSearch () {
        $where = [];
        $andWhere = [];

        $orderNumber = Yii::$app->request->get('order_number','');
        $loginName = Yii::$app->request->get('login_name',"");
        $startTime = Yii::$app->request->get('start',"");
        $endTime = Yii::$app->request->get('end',"");
        $status = Yii::$app->request->get('status',0);
        $userId = Yii::$app->request->get('user_id',0);
        if($status) {
            $where['status'] = (int) $status;
        }

        if($userId) {
            $where['user_id'] = (int) $userId;
        }

        if($orderNumber) {
            $where['order_number'] = $orderNumber;
        }

        if($loginName) {
            $userAndWhere[] = ['like','login_name',$loginName];
            $userId = User::getFormArrayAndWhere('',$userAndWhere,'id','id');
            $where['user_id'] = $userId;
        }

        if(!empty($startTime) && empty($endTime)) {
            $andWhere = ['>','create_time',$startTime];
        } elseif(empty($startTime) && !empty($endTime)) {
            $andWhere = ['<','create_time',$endTime];
        } elseif (!empty($startTime) && !empty($endTime)) {
            $andWhere = ['between','create_time',$startTime, $endTime];
        }

        return [
            'where' => $where,
            'andWhere' => $andWhere
        ];
    }

    /**
     * 处理初始化数据
     * @param $query
     * @return mixed
     */
    public function handelList($query) {
        if (empty($query)) {
            return null;
        }

        $list = $query->with([
            'user' => function($q) {
                $q->select(["id", "login_name", "user_face"]);
            },

            'bank',
        ])->asArray()->all();

        foreach($list as &$value) {
            $singleBankInfo = ArrayHelper::getValue($value,'bank',[]);
            $value['user_id'] = $value['user']['login_name'];
            $value['fee'] = round($value['fee'], 2);
            $value['money'] = round($value['money'], 2);
            $value['rate'] = $value['rate'] . "%";
            $value['status_name'] = Status::WITHDRAW_STATUS_MAP[$value['status']];
            $value['withdraw_way_name'] = Status::WITHDRAW_WAY_MAP[$value['withdraw_way']];
            $value['type_name'] = Status::WITHDRAW_TYPE_MAP[$value['type']];
            $value['bank_name'] = $singleBankInfo['bank_name'] ?: '';
            $value['card_no'] = $singleBankInfo['card_no'] ?: '';
            $value['bank_holder'] = $singleBankInfo['bank_holder'] ?: '';
        }
        return $list;
    }

    public function success() {
        $trans = Yii::$app->db->beginTransaction();
        try{
            $post = Yii::$app->request->post();
            $orderNumber = $post['order_number'];

            CacheKeys::checkFrequency('withdraw_' . $orderNumber);

            $info = static::getOneByWhere(['order_number' => $orderNumber]);
            if ($info['withdraw_way'] == Status::WITHDRAW_WAY_ALIPAY) {
                // 获取用户实名表信息
                $userKyc = UserReal::getOneByWhere(['user_id' => $info['user_id']]);
                if (empty($userKyc)) {
                    throw new Exception('该用户未实名！');
                }
               $alipayResult = (new Alipay())->userWithdraw($orderNumber, $info['alipay_account'],$userKyc['true_name']);
               if (empty($alipayResult->order_id)) {
                   throw new Exception($alipayResult->msg);
               }

                $res = static::updateData([
                    'alipay_order_id' => $alipayResult->order_id,
                    'status' => Status::WITHDRAW_STATUS_QUERYING,
                    'deal_time' => date("Y-m-d H:i:s"),
                ],['id' => $info['id']]);
                if (empty($res)) {
                    throw new Exception('支付宝提现失败！');
                }
            }

            if ($info['withdraw_way'] == Status::WITHDRAW_WAY_BANK) {
                $res = $this->successOrder($orderNumber);
            }


            $trans->commit();
            return Functions::formatRestAPI(0, '审核成功');
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }
    public function reject() {
        $trans = Yii::$app->db->beginTransaction();
        try{
            $post = Yii::$app->request->post();

            $orderNumber = $post['order_number'];

            CacheKeys::checkFrequency('withdraw_' . $orderNumber);

            $reason = $post['reason'];

            $res = $this->cancelOrder($orderNumber, $reason);

            $trans->commit();
            return Functions::formatRestAPI(0, '驳回成功');
        } catch (Exception $e) {

            $trans->rollBack();
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 获取首页金额
     * @return array
     */
    public function getMoney() {

        $andWhere = [];
        $allMoney = static::getSumByAndWhere([],$andWhere,'money');
        $applyMoney = static::getSumByAndWhere(['status' => Status::WITHDRAW_STATUS_DOING],$andWhere,'money');
        $successMoney = static::getSumByAndWhere(['status' => Status::WITHDRAW_STATUS_DONE],$andWhere,'money');
        $rejectMoney = static::getSumByAndWhere(['status' => Status::WITHDRAW_STATUS_FAILED],$andWhere,'money');
        $result = [
            'allMoney' => $allMoney ? floatval($allMoney) : 0,
            'applyMoney' => $applyMoney ? floatval($applyMoney) : 0,
            'successMoney' => $successMoney ? floatval($successMoney) : 0,
            'rejectMoney' => $rejectMoney ? floatval($rejectMoney) : 0,
        ];
        return Functions::formatRestAPI(0, '', $result);
    }
}
